#include "logworker.h"
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>
#include <QFile>
#include <QTextStream>
#include <QDir>
#include <QStandardPaths>
#include <QCoreApplication>

LogWorker::LogWorker(QObject *parent)
    : QThread(parent)
    , m_stopped(false)
    , m_autoExportThreshold(500)  // 默认500条
{
}

LogWorker::~LogWorker()
{
    stop();
    wait();  // 等待线程结束
}

void LogWorker::addLog(const LogEntry& entry)
{
    QMutexLocker locker(&m_mutex);
    m_logQueue.enqueue(entry);
    m_condition.wakeOne();  // 唤醒工作线程
}

void LogWorker::stop()
{
    QMutexLocker locker(&m_mutex);
    m_stopped = true;
    m_condition.wakeOne();  // 唤醒线程以便退出
}

void LogWorker::setAutoExportThreshold(int threshold)
{
    QMutexLocker locker(&m_mutex);
    m_autoExportThreshold = threshold;
}

int LogWorker::getCurrentLogCount()
{
    return getLogCount();
}

void LogWorker::run()
{
    // 初始化线程内的数据库连接
    if (!initDatabaseConnection()) {
        emit errorOccurred("日志工作线程: 数据库连接初始化失败");
        return;
    }

    qDebug() << "日志工作线程启动,线程ID:" << QThread::currentThreadId();

    while (true) {
        LogEntry entry;
        bool hasEntry = false;

        // 从队列中取出日志
        {
            QMutexLocker locker(&m_mutex);

            // 如果队列为空且未停止,则等待
            while (m_logQueue.isEmpty() && !m_stopped) {
                m_condition.wait(&m_mutex);
            }

            // 检查是否需要停止
            if (m_stopped && m_logQueue.isEmpty()) {
                break;
            }

            // 取出一条日志
            if (!m_logQueue.isEmpty()) {
                entry = m_logQueue.dequeue();
                hasEntry = true;
            }
        }

        // 写入数据库
        if (hasEntry) {
            if (writeLogToDatabase(entry)) {
                int currentCount = getLogCount();
                emit logWritten(currentCount);

                // 检查是否需要自动导出
                checkAndAutoExport();
            } else {
                emit errorOccurred("日志写入数据库失败");
            }
        }
    }

    // 关闭数据库连接
    if (m_database.isOpen()) {
        QString connectionName = m_database.connectionName();
        m_database.close();
        QSqlDatabase::removeDatabase(connectionName);
    }

    qDebug() << "日志工作线程结束";
}

bool LogWorker::initDatabaseConnection()
{
    QString connectionName = QString("LogWorkerConnection_%1").arg((quintptr)QThread::currentThreadId());

    if (QSqlDatabase::contains(connectionName)) {
        m_database = QSqlDatabase::database(connectionName);
    } else {
        m_database = QSqlDatabase::addDatabase("QSQLITE", connectionName);
        m_database.setDatabaseName("D:/sqlite/system.db"); // ✅ 直接指定路径
    }

    if (!m_database.isOpen() && !m_database.open()) {
        qDebug() << "❌ 日志工作线程数据库打开失败:" << m_database.lastError().text();
        return false;
    }

    qDebug() << "✅ 日志工作线程数据库连接成功:" << connectionName;
    return true;
}

bool LogWorker::writeLogToDatabase(const LogEntry& entry)
{
    QSqlQuery query(m_database);

    query.prepare("INSERT INTO system_logs (timestamp, log_type, log_level, content, user_id, device_id) "
                  "VALUES (?, ?, ?, ?, ?, ?)");

    query.addBindValue(entry.timestamp.toString("yyyy-MM-dd HH:mm:ss"));
    query.addBindValue(entry.logType);
    query.addBindValue(entry.logLevel);
    query.addBindValue(entry.content);
    query.addBindValue(entry.userId);
    query.addBindValue(entry.deviceId);

    if (!query.exec()) {
        qDebug() << "日志写入失败:" << query.lastError().text();
        qDebug() << "SQL:" << query.lastQuery();
        return false;
    }

    return true;
}

void LogWorker::checkAndAutoExport()
{
    int currentCount = getLogCount();

    if (currentCount >= m_autoExportThreshold) {
        qDebug() << QString("日志数量达到阈值(%1),开始自动导出...").arg(m_autoExportThreshold);

        // 生成导出文件路径
        QString filePath = generateExportFilePath();

        // 导出日志
        if (exportLogsToFile(filePath)) {
            // 导出成功后清空数据库
            if (clearDatabaseLogs()) {
                emit autoExportCompleted(filePath, currentCount);
                qDebug() << QString("自动导出完成: %1 条日志已导出并清空").arg(currentCount);
            } else {
                emit errorOccurred("清空数据库日志失败");
            }
        } else {
            emit errorOccurred("自动导出日志文件失败");
        }
    }
}

bool LogWorker::exportLogsToFile(const QString& filePath)
{
    QFile file(filePath);

    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        qDebug() << "无法创建导出文件:" << filePath;
        return false;
    }

    QTextStream out(&file);
    out.setCodec("UTF-8");

    // 写入文件头
    out << "========================================\n";
    out << QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss") << "\n";
    out << "========================================\n\n";

    // 写入表头
    out << QString("%1\t%2\t%3\t%4\t%5\t%6\t%7\n")
           .arg("日志ID", -8)
           .arg("时间戳", -19)
           .arg("日志类型", -10)
           .arg("日志级别", -8)
           .arg("内容", -50)
           .arg("用户ID", -8)
           .arg("设备ID", -8);

    out << QString().fill('-', 120) << "\n";

    // 查询所有日志
    QSqlQuery query(m_database);
    if (!query.exec("SELECT log_id, timestamp, log_type, log_level, content, user_id, device_id "
                   "FROM system_logs ORDER BY log_id")) {
        qDebug() << "查询日志失败:" << query.lastError().text();
        file.close();
        return false;
    }

    int recordCount = 0;
    while (query.next()) {
        QString logId = query.value(0).toString();
        QString timestamp = query.value(1).toString();
        QString logType = query.value(2).toString();
        QString logLevel = query.value(3).toString();
        QString content = query.value(4).toString();
        QString userId = query.value(5).toString();
        QString deviceId = query.value(6).toString();

        // 清理内容中的换行符和制表符
        content = content.replace("\n", " ").replace("\t", " ");

        // 限制内容长度
        if (content.length() > 100) {
            content = content.left(100) + "...";
        }

        out << QString("%1\t%2\t%3\t%4\t%5\t%6\t%7\n")
               .arg(logId, -8)
               .arg(timestamp, -19)
               .arg(logType, -10)
               .arg(logLevel, -8)
               .arg(content, -50)
               .arg(userId, -8)
               .arg(deviceId, -8);

        recordCount++;
    }

    // 写入文件尾
    out << "\n========================================\n";
    out << QString("总计导出 %1 条日志记录\n").arg(recordCount);
    out << "========================================\n";

    file.close();

    qDebug() << QString("导出完成: %1 条记录 -> %2").arg(recordCount).arg(filePath);
    return true;
}

bool LogWorker::clearDatabaseLogs()
{
    QSqlQuery query(m_database);

    if (!query.exec("DELETE FROM system_logs")) {
        qDebug() << "清空日志表失败:" << query.lastError().text();
        return false;
    }

    // 重置自增ID(SQLite特定)
    if (!query.exec("DELETE FROM sqlite_sequence WHERE name='system_logs'")) {
        qDebug() << "重置自增ID失败:" << query.lastError().text();
        // 这不是致命错误,继续执行
    }

    qDebug() << "数据库日志已清空";
    return true;
}

int LogWorker::getLogCount()
{
    QSqlQuery query(m_database);

    if (query.exec("SELECT COUNT(*) FROM system_logs")) {
        if (query.next()) {
            return query.value(0).toInt();
        }
    }

    return 0;
}

QString LogWorker::generateExportFilePath()
{
    // 固定路径：D:\qt\Documents\day12_04_system\SystemLogs\AutoExport
    QString exportDir = QStringLiteral("D:/qt/Documents/day12_04_system/SystemLogs/AutoExport");

    QDir dir;
    if (!dir.exists(exportDir)) {
        dir.mkpath(exportDir);          // 若目录不存在则一次性建全
    }

    QString fileName = QStringLiteral("系统日志_自动导出_%1.txt")
                           .arg(QDateTime::currentDateTime().toString("yyyyMMdd_HHmmss"));

    return exportDir + "/" + fileName;  // 最终完整路径
}
